package com.katze.boot.file.init;

import com.katze.boot.file.entity.FileRepositoryEntity;
import com.katze.boot.file.registry.FileSystemRegistrationBean;
import com.katze.boot.file.service.FileRepositoryService;
import com.katze.boot.file.servlet.DefaultFileTransferServlet;
import com.katze.boot.file.servlet.DefaultFileUploadService;
import com.katze.common.env.AppEnvironment;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DefaultFileTransferConfiguration {

    @Bean
    public ServletRegistrationBean<DefaultFileTransferServlet> servletRegistrationBean(FileRepositoryService fileRepositoryService) {
        FileRepositoryEntity entity = fileRepositoryService.getDefaultFileRepository();
        String temp = entity == null || StringUtils.isBlank(entity.getTempPath())? AppEnvironment.TEMP_DIR.getValue():entity.getTempPath();
        return new ServletRegistrationBean<>(new DefaultFileTransferServlet(temp), "/file/upload");
    }

    @Bean
    public DefaultFileUploadService defaultFileUploadService(ServletRegistrationBean<DefaultFileTransferServlet> servletRegistrationBean) {
        return new DefaultFileUploadService(servletRegistrationBean);
    }

    @Bean
    public FileSystemRegistrationBean transferRegistrationBean() {
        return new FileSystemRegistrationBean();
    }
}
